package com.example.util;

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;

import java.io.InputStream;

public class UploadUtil {
    //    阿里云用户AccessKey ID
    private static final String KEY = "LTAI5tGHfcrJn4NtRnbLrtM2";
    //    阿里云用户AccessKey Secret
    private static final String SECRET = "UGyJZ28pE9jbJIu8x36lJNh5WhVAf0";
    // 存储的服务器地址
    private static final String endpoint = "https://oss-cn-beijing.aliyuncs.com";
    // Bucket名称
    private static final String bucketName = "file-upload02";
    // Bucket所在地域
    private static final String region = "cn-beijing";

    public static void filerUpload(String fileName, InputStream inputStream) {
        // 获取访问凭证
        DefaultCredentialProvider defaultCredentialProvider = new DefaultCredentialProvider(KEY, SECRET);
        // 创建OSSClient实例。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(defaultCredentialProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();
        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, inputStream);
            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
        } catch (OSSException oe) {
            System.out.println("捕获到了一个 OSS 异常，这意味着您的请求已到达对象存储服务（OSS），“但由于某些原因被拒绝并返回了错误响应");
            System.out.println("错误信息:" + oe.getErrorMessage());
            System.out.println("错误代码:" + oe.getErrorCode());
            System.out.println("请求ID:" + oe.getRequestId());
            System.out.println("主机 ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("捕获到了一个客户端异常，这意味着客户端在尝试与对象存储服务（OSS）进行通信时遇到了严重的内部问题，比如无法访问网络。");
            System.out.println("错误信息:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

    }
} 